(function ($) {
	var me = {};
	var Form = function(element, options) {
		this.element = $(element);
		me = this;
		$.each(options,function(k,v){
			if( v == undefined && v == null ) return true;
			if( typeof v === 'object' ) {
				$.extend(me.get(k),v);
			} else {
				me.set(k,v);
			}
		});
	};
	// 默认配置
	Form.prototype = {
		constructor: Form,
		// 设置
		set: function(key,val){
			this[key] = val;
			return this;
		},
		// 获取
		get: function(key){
			return this[key];
		},
		// 是否自动加载
		autoLoad: true,
		// 主键字段
		pkField: "id",
		// 请求地址
		modularPath: {
			editUrl: "",
			insertUrl: "",
			updateUrl: "",
		},
		// 表单元素配置
		FormOption: [],
		// 表单元素模板
		FormElementTpl: '',
		// 创建表单元素
		createFormElement: function(){
			var formElementSettings = {
				elementOption: me.FormOption,
				//elementTpl: me.FormElementTpl
			};
			me.element.formElement(formElementSettings);
		},
		// 修改的数据
		editData: {},
		// url参数
		urlParams: {},
		// 获取url参数
		getUrlParams: function(){
			var url = window.location.href, pos = url.indexOf('?'), params = url.substring(pos+1,url.length);
			var result = {};
			if( pos != -1 )
				result = me.urlParams = me.paramString2obj(params);
			return result;
		},
		// 按钮列表
		buttons: ['back','submit','reset'],
		// 按钮背景div元素
		buttonBackdrop: '<div class="space-4"></div>' +
						'<div class="clearfix form-actions">' +
							'<div class="col-md-offset-3 col-md-9">' +
							'{0}' +
							'</div>' +
						'</div>',
		// 按钮div元素
		buttonTpl: '<button class="{3}" id="{0}" type="button">' +
						'<i class="ace-icon fa {1} bigger-110"></i>' +
						'{2}' +
					'</button>',
		// 返回按钮
		backButton:{
			enable: true,
			id: "btnBack",
			title: '返回',
			icon: "fa-reply",
			className: "btn",
			buttonTpl: "",
		},
		// 返回操作
		backAction: function(){
			window.history.go(-1);
		},
		// 提交按钮
		submitButton: {
			enable: true,
			pk: 'id',
			id: "btnSubmit",
			title: '提交',
			icon: "fa-check",
			className: "btn btn-info",
			buttonTpl: "",
		},
		// 提交操作
		submitAction: function(){
			var $form = me.element;
			var pkValue = $form.find("input[name=" + me.pkField + "]").val();
			var url = ( pkValue == undefined || pkValue == '' ) ? me.modularPath.insertUrl : me.modularPath.updateUrl;
			var enctype = $form.attr('enctype');
			var formData = $form.serializeArray();
			if( enctype == "multipart/form-data" ) {
				formData = new FormData($form[0]);
			} else  {
				delete me.submitAjaxOption.contentType;
				delete me.submitAjaxOption.processData;
			}
			me.submitAjaxOption.url = url;
			me.submitAjaxOption.data = formData;
			$.ajax(me.submitAjaxOption);
		},
		// 重置按钮
		resetButton: {
			enable: true,
			id: "btnReset",
			title: '重置',
			icon: "fa-undo",
			className: "btn",
			buttonTpl: "",
		},
		// 重置操作
		resetAction: function(){
			var $form = me.element;
			$form[0].reset();
		},
		// 创建按钮
		createButtons: function(){
			var html = '', $form = me.element;
			$.each(me.buttons,function(k,v){
				var val = me[v + 'Button'];
				// 未启用则退出本次循环
				if( !val['enable'] ) return true;
				var _id = val.id || "", _icon = val.icon || "", _title = val.title || "", _className = val.className || "";
				html += val.buttonTpl != "" ? val.buttonTpl.format(_id,_icon,_title,_className) : me.buttonTpl.format(_id,_icon,_title,_className);
				html += '&nbsp; &nbsp; &nbsp;';
			});
			html = me.buttonBackdrop.format(html);
			me.element.append(html);
			// 绑定操作事件
			$.each(me.buttons,function(k,v){
				var val = me[v + 'Button'];
				if( !val['enable'] ) return true;
				var _event = me[v + 'Action'] || function(){};
				$("#" + val.id).on('click', function(){
					_event();
				});
			});
		},
		showMsg: function(msg,buttons){
			var buttons = buttons || ['success'];
			var btnConfig = {
				success: {
					label: "确定",
					className: "btn-sm btn-primary",
					callback: function(){
						//me.objGrid.ajax.reload();
					}
				},
				cancel: {
					label: "取消",
					className: "btn-sm",
				}
			};
			var dialogOption = {
				message: msg,
				buttons: {}
			};
			$.each(buttons,function(key,val){
				dialogOption.buttons[val] = btnConfig[val];
			});
			bootbox.dialog(dialogOption);
		},
		// 创建菜单的 Element
		createFormEle:function(args){
			var data = me.editData;
			$.each(data,function(key,val){
				$("[name='"+key+"']").val(val);
			});
		},
		// 获取修改页数据 - 异步请求参数
		editAjaxOption: {
			type: "get",
			dataType: "json",
			url: "",
			data: "",
			async: false,
			success: function(data){
				me.editSuccess(arguments);
				$.extend(me.editData, data.result, me.urlParams);
				me.createFormEle();
			},
			error: function(data){
				me.editError(arguments);
			}
		},
		// 获取修改页数据加载成功
		editSuccess: function(args){},
		// 获取修改页数据加载失败
		editError: function(args){},
		// 提交数据 - 异步请求参数
		submitAjaxOption: {
			type: "post",
			dataType: "json",
			url: "",
			data: "",
			async: false,
			cache: false,
			contentType: false,
			processData: false,
			success: function(data){
				console.log(data);
				me.submitSuccess(data);
			},
			error: function(data){
				me.submitError(arguments);
			}
		},
		// 提交数据加载成功
		submitSuccess: function(data){
			me.showMsg(data['msg']);
			if( data['isOk'] == 1 ) {
				window.history.go(-1);
			}
			console.log(data);
		},
		// 提交数据加载失败
		submitError: function(args){
			console.log(args);
		},
		// 创建Element
		load: function(data){
			var params = me.getUrlParams();
			me.beforeLoad();
			me.createFormElement();
			me.createButtons();
			// 修改时获取数据
			/*if( params[me.pkField] != undefined && params[me.pkField] != '' ) {
				me.editAjaxOption.url = me.modularPath.editUrl;
				me.editAjaxOption.data = params;
				$.ajax(me.editAjaxOption);
			}*/
			me.afterLoad();
		},
		// 加载数据前操作
		beforeLoad: function(){},
		// 加载数据之后操作
		afterLoad: function(){},
		// a=1&b=2转换成{a:1,b:2}
		paramString2obj: function(params){
			var array = params.split("&");
			var obj = {};
			for (var i = 0, len = array.length; i < len; i++) {
				var item = array[i].split("=");
				obj[item[0]] = item[1];
			}
			return obj;
		},
		// {a:1,b:2}转换成a=1&b=2
		obj2paramString: function(obj){
			return $.param(obj);
		},
	};
    /**
     * 扩展 Jquery 对象为 Form
     * @param option
     */
	$.fn.form = function(option){
		return this.each(function () {
			var $this = $(this),
			   data = $this.data('form'),
			   options = typeof option === 'object' && option;
			if (!data)  {
				$this.data('form', (data = new Form(this, $.extend({}, options))));
			}
			if (typeof option == 'string') {
				data[option]();
			}
			if(data.autoLoad){
				data.load();
			}
		});
	};
	// 属性返回对创建此对象的函数的引用
	$.fn.form.Constructor = Form;

})(jQuery);



